package com.shenma2009;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 军哥
 * @version 1.0
 * @description: TestLockApp
 * @date 2023/5/25 11:34
 */

public class TestLockApp implements Runnable{

    private static Integer _count = 0;
    private Lock _lock = null;

    TestLockApp(Lock lock) {
        _lock = lock;
    }

    @Override
    public void run() {


        try {
            Thread.sleep(1000);
            for (int i = 0; i < 100; i++) {

                _lock.lock();
                try {
                    _count ++;
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    _lock.unlock();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        System.out.println(Thread.currentThread().getName()+",_count="+_count);
    }

    public static void main(String[] args) throws InterruptedException {

        ReentrantLock lock = new ReentrantLock();

        // 创建线程
        Thread thread1 = new Thread(new TestLockApp(lock));
        Thread thread2 = new Thread(new TestLockApp(lock));
        Thread thread3 = new Thread(new TestLockApp(lock));

        // 运行线程
        thread1.start();
        thread2.start();
        thread3.start();

        //
        thread1.join();
        thread2.join();
        thread3.join();

        //
        System.out.println("count="+TestLockApp._count);
    }
}
